package net.sf.jxls.sample.hall;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.*;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author duhongming
 * @Email 19919902414@189.cn
 * @Date 2018/6/28 14:56
 */
public class 营业厅售卡情况报表demo {

    private static String templateFileName = System.getProperty("user.dir")+"/dhm-datatables-jxls1/templates/BusinessHallCardList.xlsx";
    private static String destFileName = System.getProperty("user.dir")+"/dhm-datatables-jxls1/templates/营业厅售卡情况报表_output.xlsx";

    public static void main(String[] args) throws IOException {
        String json = new String(Files.readAllBytes(Paths.get("E://test.json")));
        final Type type = new TypeReference<List<CardBusinessReport>>(){}.getType();
        List<CardBusinessReport> results = JSON.parseObject(json,type);
        List<GroupList<CardBusinessReport>> groupList = CardBusinessReportService.toGroupData(results);

        Map<String,Object> beans = new HashMap<String,Object>();

        beans.put("results",groupList);
        beans.put("total",CardBusinessReportService.get(results));

        long start = System.currentTimeMillis();
        try(InputStream inputStream = new FileInputStream(templateFileName)) {
            XLSTransformer transformer = new XLSTransformer();
            Workbook workbook = transformer.transformXLS(inputStream, beans);
            for(int i=0;i<workbook.getNumberOfSheets();i++){
                Sheet sheet = workbook.getSheetAt(i);
                int firstRow = 3;
                int lastRow = 0;
                for(int j=0;j<groupList.size();j++){
                    GroupList<CardBusinessReport> cardBusinessReportGroupList = groupList.get(j);
                    int size = cardBusinessReportGroupList.getGroupList().size();
                    lastRow = firstRow+(size-1);
                    sheet.addMergedRegion(new CellRangeAddress(firstRow+j,(short)lastRow+j+1,0,(short)0));
                    firstRow = lastRow + 1;
                }
            }
            OutputStream os = new BufferedOutputStream(new FileOutputStream(destFileName));
            workbook.write(os);
            os.flush();
            os.close();
        }catch (Exception e){

        }
        long end = System.currentTimeMillis();
        System.out.println("end-start = " + (end - start));
    }
}